package com.example.core.upload;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.example.core.upload.DTO.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * @ClassName UploadController
 * @Author zhangzhaoyang
 * @Date 2019/9/27 16:34
 **/
@RequestMapping("/upload")
@RestController
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    /**
     * 实现文件上传
     * */
    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            return "上传Excel文件不能为空";
        }
////        返回文件的大小,以字节为单位。
//       long fileSize =  file.getSize();
//        System.out.println("====返回文件的大小,以字节为单位====="+fileSize);
////返回InputStream读取文件的内容
//        InputStream fileSizeInputStream = file.getInputStream();
//        System.out.println("====返回InputStream读取文件的内容====="+fileSizeInputStream);
//
//        String fileName =  file.getOriginalFilename();

        try {

            List<Object[]> list = ExcelUtils.importExcel(file.getInputStream());
            List<User> listUser = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                User user = new User();
                user.setId((Integer) list.get(i)[0]);
                user.setUsername((String) list.get(i)[1]);
                user.setPassword((String) list.get(i)[2]);
                user.setEnable((Integer) list.get(i)[3]);
                listUser.add(user);
                System.out.println(user.toString());

            }
            return listUser.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "上传Excel文件解析出错"+e.getMessage();
        }
    }
}
